package and.example.data;

import and.example.interfaces.IArguments;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DatabaseConnector implements IArguments {

	private SQLiteDatabase database;
	private DatabaseOpenHelper databaseOpenHelper;

	public DatabaseConnector(Context ctx) {
		databaseOpenHelper = new DatabaseOpenHelper(ctx, DATABASE_NAME, null, 5);
	}

	public Cursor getAllContacts() {
		//open();
		Cursor cursor = database.query(COLUMNS[0], new String[] { COLUMNS[1],
				COLUMNS[2], COLUMNS[3], COLUMNS[7] }, null, null, null, null,
				COLUMNS[2]);
		//close();
		return cursor;
	}

	public void open() {

		try {

			database = databaseOpenHelper.getWritableDatabase();
		} catch (Exception e) {
			Log.e("Loi DatabaseConnector==>", "Loi ham open : mo database", e);
		}

	}

	public void close() {
		if (database != null) {
			database.close();
		}
	}

	public Cursor getOneContact(Long id) {
		return database.query(COLUMNS[0], null, COLUMNS[1] + "=" + id, null,
				null, null, null);
	}

	public void deleteContact(Long id) {

		try {

			open();
			database.delete(COLUMNS[0], COLUMNS[1] + "=" + id, null);
			close();

		} catch (Exception e) {
			Log.e("Loi DatabaseConnector==>",
					"Loi ham deleteContact : mo database", e);
		}

	}

	public void insertContact(Contact contact) {

		try {

			ContentValues cv = new ContentValues();
			cv.put(COLUMNS[2], contact.getName());
			cv.put(COLUMNS[3], contact.getPhone());
			cv.put(COLUMNS[4], contact.getEmail());
			cv.put(COLUMNS[5], contact.getStreet());
			cv.put(COLUMNS[6], contact.getCity());
			cv.put(COLUMNS[7], contact.getImage());

			open();
			database.insert(COLUMNS[0], COLUMNS[7], cv);
			close();
		} catch (Exception e) {
			Log.e("Loi DatabaseConnector==>",
					"Loi ham insertContact : mo database", e);
		}

	}

	public void updateContact(long id, Contact contact) {

		try {

			ContentValues cv = new ContentValues();
			cv.put(COLUMNS[2], contact.getName());
			cv.put(COLUMNS[3], contact.getPhone());
			cv.put(COLUMNS[4], contact.getEmail());
			cv.put(COLUMNS[5], contact.getStreet());
			cv.put(COLUMNS[6], contact.getCity());
			cv.put(COLUMNS[7], contact.getImage());

			open();
			database.update(COLUMNS[0], cv, COLUMNS[1] + "=" + id, null);
			close();
		} catch (Exception e) {
			Log.e("Loi DatabaseConnector==>",
					"Loi ham updateContact : mo database", e);
		}

	}

}
